package servlet;

import com.alibaba.fastjson.JSON;
import entity.Msg;
import entity.User;
import org.apache.commons.beanutils.BeanUtils;
import service.IAdminService;
import service.imp.AdminService;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.lang.reflect.InvocationTargetException;
import java.util.HashMap;
import java.util.Map;

public class AdminServlet extends javax.servlet.http.HttpServlet {
    private IAdminService service = new AdminService();
    protected void doPost(javax.servlet.http.HttpServletRequest request, javax.servlet.http.HttpServletResponse response) throws javax.servlet.ServletException, IOException {
        doGet(request, response);
    }


    protected void doGet(javax.servlet.http.HttpServletRequest request, javax.servlet.http.HttpServletResponse response) throws javax.servlet.ServletException, IOException {
        response.setCharacterEncoding("utf-8");
        response.setContentType("application/json;charset=utf-8");
        String method = request.getParameter("method");
        if ("getHome".equals(method)) {
            getHome(request, response);
        } else if ("getUser".equals(method)) {
            getUser(request, response);
        } else if ("login".equals(method)) {
            doLogin(request,response);
        } else if ("getUserInfo".equals(method)) {
            getUserInfo(request, response);
        } else if ("updateUser".equals(method)) {
            updateUser(request, response);
        } else if ("deleteUser".equals(method)) {
            deleteUser(request, response);
        } else if ("register".equals(method)) {
            doRegister(request, response);
        } else {
            getDefault(request, response);
        }
    }

    private void doRegister(HttpServletRequest request, HttpServletResponse response) {
        try {
            request.setCharacterEncoding("UTF-8");
            Map<String, String[]> paramaters = new HashMap<>(request.getParameterMap());
            paramaters.remove("method");
            User u = new User();
            BeanUtils.populate(u, paramaters);
            String responseString = service.doRegister(u);
            response.getWriter().print(responseString);
        } catch (UnsupportedEncodingException | IllegalAccessException | InvocationTargetException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }

    }

    private void deleteUser(HttpServletRequest request, HttpServletResponse response) {
        int uid = Integer.parseInt(request.getParameter("uid"));
        String responseString = service.deleteUser(uid);
        try {
            response.getWriter().print(responseString);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    private void updateUser(HttpServletRequest request, HttpServletResponse response) {
        try {
            request.setCharacterEncoding("UTF-8");
            Map<String, String[]> paramaters = new HashMap<>(request.getParameterMap());
            paramaters.remove("method");
            User u = new User();
            BeanUtils.populate(u, paramaters);
            String reponseString = service.updateUserInfo(u);
            response.getWriter().print(reponseString);
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        } catch (InvocationTargetException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    private void getUserInfo(HttpServletRequest request, HttpServletResponse response) {
        Cookie[] cookies = request.getCookies();
        int uid = -1;
        if (cookies != null) {
            for (Cookie c : cookies) {
                if ("uid".equals(c.getName())) {
                    uid = Integer.parseInt(c.getValue());
                }
            }
        }
        String responseString = null;
        if (uid > 0) {
            responseString = service.getUserByUid(uid);
        } else {
            Msg msg = new Msg(404, "get failed");
            responseString = JSON.toJSONString(msg);
        }
        try {
            response.getWriter().print(responseString);
        } catch (IOException e) {
            e.printStackTrace();
        }

    }

    private void doLogin(HttpServletRequest request, HttpServletResponse response) {
        /**
         *1.从前端拿到的数据构建User对象
         * 2.调用Dao层注册的方法
         */
        String username = request.getParameter("username");
        String password = request.getParameter("password");
//        System.out.println(username + " " + password);
        User admin = new User();
        admin.setUsername(username);
        admin.setPassword(password);
        int rs = service.doLogin(admin);
        String responseString = "{\"msg\":404}";
        if (rs > 0) {
            responseString = "{\"msg\":200}";
            Cookie cookie = new Cookie("uid", Integer.toString(rs));
            cookie.setMaxAge(1000 * 60 * 24);
            response.addCookie(cookie);
        }
        try {
            response.getWriter().print(responseString);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    private void getUser(HttpServletRequest request, HttpServletResponse response) {
        String responseString = service.getUser();
        try {
            response.getWriter().print(responseString);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    private void getDefault(HttpServletRequest request, HttpServletResponse response) {
        try {
            Msg msg = new Msg(404, "接口错误或权限越界!=>也可能是你没有重启服务器哦<=");
            response.getWriter().print(JSON.toJSONString(msg));
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    private void getHome(HttpServletRequest request, HttpServletResponse response) {
        String date = service.getAdminHome();
        try {
            response.getWriter().print(date);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
